import os
from threading import Lock, Thread
from time import sleep

import sys
import webview
from apscheduler.triggers import cron

from server import run_server
from tools.linq import linq
from tools.scheduler import MyScheduler
from tools import i18n, convert

server_lock = Lock()

# logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG)

import logging.config

logging.config.fileConfig('logging.conf')

logger = logging.getLogger(__name__)

os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = '3333'


def url_ok(url, port):
    # Use httplib on Python 2
    try:
        from http.client import HTTPConnection
    except ImportError:
        from httplib import HTTPConnection

    try:
        conn = HTTPConnection(url, port)
        conn.request("GET", "/")
        r = conn.getresponse()
        return r.status == 200
    except:
        logger.exception("Server not started")
        return False


def fullsc():
    sleep(1)
    webview.toggle_fullscreen()


if __name__ == '__main__':
    from tools.globalvar import get_i18nvalue as translate

    print(cron)
    logger.debug("Starting server")
    t = Thread(target=run_server)
    t.daemon = True
    t.start()
    logger.debug("Checking server")

    sleep(1)
    while not url_ok("127.0.0.1", 9999):
        sleep(1)

    webview.config.use_qt = True

    # logger.debug("Server started")
    # p = Thread(target=fullsc)    # p.start()

    # 持续ping
    import tools.pinger

    if not linq(sys.argv).any(lambda x: x in ("noping", "debug")):
        tools.pinger.keep_ping()

    # weather.getweather()
    MyScheduler.start()

    # 根据语言初始化后台使用的翻译包信息并存入全局使用类变量里，当前测试传入语言写死的，后期会从某个地方动态获取
    i18n.i18n_backstage('en_US', os.getcwd())

    # #获取系统参数
    # init=initsysparam()
    # init.init_sysparam()

    if linq(sys.argv).any(lambda x: x == "debug"):
        import webbrowser

        webbrowser.open("http://127.0.0.1:9999/fastapi_doc")
        while True:
            sleep(1)
    else:
        webview.create_window("FC-POS", "http://127.0.0.1:9999", min_size=(1027, 768))
